---
--类名: SecretView.lua
--创建日期: 2018-6-15
--创建人: 宋建邦
--功能描述: 秘境视图
--
local MoLayer = require("app.widget.MoLayer")
local UIUtil = require("app.utils.UIUtil")
local AvatarFactotry = require("app.public.avatar.AvatarFactory")
local TeamModel = app:getInst("TeamModel")
local PvpLevelView = require("app.pvp.views.PvpLevelView")
local PvpSeasonInfo = require("app.pvp.models.PvpSeasonInfo")

local SecretView = class("SecretView", function()
    return MoLayer.new(true)
end)

-- local Res = {
--     SecretScene = "ui2/secret/Scene_secret.csb",
--     LevelUpNode = "ui2/secret/ani_refurbish.csb",
-- }

function SecretView:ctor(achType, labelType)
    self.vsEvent = 1
    self.vsFoot = 2

    self:setNodeEventEnabled(true)
    
    self.mUINode = cc.uiloader:load(Res.SecretScene)
    self:addChild(self.mUINode)
    self.mUINode:setContentSize(cc.size(display.width, display.height))
    ccui.Helper:doLayout(self.mUINode)
    
    self:addCloseListener()

    self.titleDataLbl = self.mUINode:findChild("Panel/data")
    self.mUINode:findChild("Panel/Panel_tlt/tlt"):setString(L"SecretDungeon_1")

    self.touchNode = self.mUINode:findChild("Panel/Panel_race")
    self.touchNode:setTouchEnabled(true)
    self.touchNode:addTouchEventListener(function(sender,eventType)
        if eventType == ccui.TouchEventType.ended then
            local curGrade = protobuf.enum_id("pb_secretDungeon.REWARD", SecretManager.info.grade)
            if curGrade < 3 then
                app:sendMsg("NewDungeonTypeController", "openMatchingView", 4)
            end
        end
    end)

    --Panel_race
    self.racePanel = self.mUINode:findChild("Panel/Panel_race") 
    self.layerLbl = self.mUINode:findChild("Panel/Panel_race/tlt")
    self.layerNameLbl = self.mUINode:findChild("Panel/Panel_race/text")

    self.cups = {
        self.mUINode:findChild("Panel/Panel_race/node_1"),
        self.mUINode:findChild("Panel/Panel_race/node_2"),
        self.mUINode:findChild("Panel/Panel_race/node_3"),
    }
    self.cup_bgs = {
        self.mUINode:findChild("Panel/Panel_race/bg1"),
        self.mUINode:findChild("Panel/Panel_race/bg2"),
        self.mUINode:findChild("Panel/Panel_race/bg3"),
    }

    for i, v in ipairs(self.cups) do
        v:findChild("Panel"):addTouchEventListener(function(sender)
            UIUtil.showTips(self, v:findChild("Panel/bg"), {
                name=L("secretDungeontips1"),
                desc1=L("secretDungeontips2"),
            })

        end)
    end

    self.aniNode = self.mUINode:findChild("Panel/ani_refurbish")
    self.aniNode:hide()
    self.lockBtn = self.mUINode:findChild("Panel/Panel_race/Button_lock")
    self.lockBtn:addClickEventListener(function()
        SecretManager:reqestActiveNextLayer()
    end)

    self.battBtn = self.mUINode:findChild("Panel/Panel_race/Button_batt")
    self.battBtn:addClickEventListener(function()
        app:sendMsg("NewDungeonTypeController", "openMatchingView", 4)
    end)

    --Panel_max
    self.maxPanel = self.mUINode:findChild("Panel/Panel_max")
    self.maxPanelLayerLbl = self.mUINode:findChild("Panel/Panel_max/num")
    self.maxPanelDescLbl = self.mUINode:findChild("Panel/Panel_max/text")
    self.maxPanel:setTouchEnabled(true)
    self.maxPanel:addTouchEventListener(function(sender,eventType)
        if eventType == ccui.TouchEventType.ended then
            -- app:sendMsg("NewDungeonTypeController", "openMatchingView", 4)
        end
    end)


    --Panel_bom
    -- self.curLvLbl = self.mUINode:findChild("Panel/Panel_bom/")
    self.curLvLbl = self.mUINode:findChild("Panel/Panel_bom/num")
    self.curLvTitleLbl = self.mUINode:findChild("Panel/Panel_bom/tlt_2")
    self.curLvProcessLbl = self.mUINode:findChild("Panel/Panel_bom/exp")
    self.curLvLoadingBar = self.mUINode:findChild("Panel/Panel_bom/bar_2/LoadingBar")
    self.curLvTips = self.mUINode:findChild("Panel/Panel_bom/bar_2/bg1")
    self.curLvTips:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            local dataTemp = {
                name = L("secretDungeontips5"),
                desc = L("secretDungeontips6"),
                notice = L("tips_3000412")
            }
            local rewards = {}
            local level = tonumber(self.curLvLbl:getString())
            if level and level > 0 then
                local conf = GD:getDungeonSecretModeConfigById(level)
                if conf then
                    local dropIds = string.split(conf.seasonReward, ";")
                    for _, dropId in ipairs(dropIds) do
                        local rets = UD:parseDropIDToBagItem(dropId)
                        if rets then
                            for _, itemData in ipairs(rets) do
                                table.insert(rewards, itemData)
                            end
                        end
                    end
                end
            end
            dataTemp.rewards = rewards

            local distanceX = self.curLvTips:getContentSize2()
            UIUtil.showBoxTipsView(self, self.curLvTips, dataTemp, distanceX)
        end
    end)

    self.taskTitleLbl = self.mUINode:findChild("Panel/Panel_bom/tlt_1")
    self.taskProcessLbl = self.mUINode:findChild("Panel/Panel_bom/cup_num")
    self.taskLoadingBar = self.mUINode:findChild("Panel/Panel_bom/bar_1/LoadingBar")

    self.taskMask = self.mUINode:findChild("Panel/Panel_bom/Panel_icon/mask")
    self.taskFinished = self.mUINode:findChild("Panel/Panel_bom/Panel_icon/open")
    self.taskLock = self.mUINode:findChild("Panel/Panel_bom/Panel_icon/lock")
    self.taskIcon = self.mUINode:findChild("Panel/Panel_bom/Panel_icon/icon")
    self.taskIcon2 = self.mUINode:findChild("Panel/Panel_bom/Panel_icon/icon_2")

    self.taskIcon:setTouchEnabled(true)
    self.taskIcon:addTouchEventListener(function(sender,eventType)
        if eventType == ccui.TouchEventType.ended then
            -- if self.lastClick and app.getTime() - self.lastClick < 5 then
            --     display.pushToast( L("操作过于频繁") )
            --     return
            -- end
            -- self.lastClick = app.getTime()
            if SecretManager:hasSecretTaskReward() then
                app:sendMsg("BoxController", "openView", { boxType = Enums.BoxType.secret, taskIndex = SecretManager:getCurrentSecretTaskIndex() })
            else

                local dataTemp = {
                    name = L("secretDungeontips3"),
                    -- desc = L("secretDungeontips4"),
                    notice = L("tips_3000413"),
                }

                -- 查询当前奖励
                local ft = SecretManager:getCurrentSecretTask()
                if ft then
                    dataTemp.rewards = UD:parseDropIDToBagItem(ft.dropId)
                end
                
                UIUtil.showBoxTipsView(self, self.taskIcon, dataTemp)
            end
        end
    end)

    self.backgroundImg = self.mUINode:findChild("Panel/img")

    self.taskProcessLbl:setString("1/2")
    self:refreshInfo()

    self._secretInfoChangeHandler = EM:on(SecretManager.EvtSecretInfoChange, handler(self, self.refreshInfo))
    EM:on(SecretManager.EvtSecretActiveNextLayer, handler(self, self.showLevelUpEffect))

    -- self:checkFirseSeason() 
    self:checkLevelUpPop()
    SecretManager:reqestSecretInfo()   
end

function SecretView:onExit()
    EM:remove(self._secretInfoChangeHandler)
    EM:removeByName(SecretManager.EvtSecretActiveNextLayer)
end

-- function SecretView:checkFirseSeason()
--     local info = SecretManager.info
--     local isFirstShow = app:getValue("secretFirstSeasonShowed", false)
--     if info and info.lv == 1 and info.layer == 1 and isFirstShow == false then
--         self:showNewSeasonPopView()
--         app:saveValue("secretFirstSeasonShowed", true)
--     end
-- end

function SecretView:checkLevelUpPop()
    local lvUp = app:getValue(SecretManager.LSKey, false)
    if SecretManager.info and lvUp then
        SecretManager:showLevelUpView(SecretManager.info)
        app:saveValue(SecretManager.LSKey, false)
    end
end

function SecretView:refreshMaxPanel()
    local msg = SecretManager.info

    self.maxPanel:show()
    self.racePanel:hide()

    self.maxPanelLayerLbl:setString(tostring(math.min(SecretManager.maxConfigLayer, msg.initLayer + SecretManager.maxLayer) ))
    self.maxPanelDescLbl:setString( string.format(L("lua_code_text_252"), tostring( math.max(1, msg.layer - 5))))
end

function SecretView:showLevelUpEffect()
    local lvUpAction = cc.CSLoader:createTimeline(Res.LevelUpNode)
    lvUpAction:play("animation0", false)
    self.aniNode:show()
    self.aniNode:runAction(lvUpAction)
    lvUpAction:setLastFrameCallFunc(function()
        self.aniNode:hide()
        lvUpAction:clearLastFrameCallFunc()
    end)
end

function SecretView:refreshInfo()
    self.maxPanel:hide()
    self.racePanel:hide()
    if not SecretManager.info then
        return
    end

    self.racePanel:show()

    local msg = SecretManager.info

    if self.seasonReward == nil and msg.seasonReward and checknumber(msg.lastSeasonLv) > 0 then
        self.seasonReward = true
        self:showNewSeasonPopView()
    end

    self.layerNameLbl:setString(SecretManager:getCurrentCopyName())

    self.lockBtn:hide()
    self.battBtn:hide()
    --激活下一层条件 金杯
    local curGrade = protobuf.enum_id("pb_secretDungeon.REWARD", msg.grade)
    if curGrade >= 3 then
        self.lockBtn:show()
    else
        self.battBtn:show()
    end

    self.secretConfig = GD:getDungeonSecretModeConfigById(msg.layer)
    self.levelConfig = GD:getDungeonSecretModeConfigById(msg.lv)
    if not self.secretConfig then
        print("no secret mode config, id:", msg.layer)
        return
    end

    local sd = os.date("*t", msg.startTime)
    local ed = os.date("*t", msg.endTime)
    self.titleDataLbl:setString(tostring(sd.month).."."..tostring(sd.day).."-"..tostring(ed.month).."."..tostring(ed.day))

    local strCurLayer = string.format(L("lua_code_text_499"), tostring(msg.layer))
    self.layerLbl:setString(strCurLayer)

    self.curLvLbl:setString(tostring(msg.lv))
    if msg.initLv + SecretManager.maxLevel <= msg.lv then
        self.curLvTitleLbl:setString(L("lua_code_text_312"))
    else
        self.curLvTitleLbl:setString(string.format(L("lua_code_text_330"), tostring(math.min(msg.initLv + SecretManager.maxLevel, SecretManager.maxConfigLayer))))
    end
    
    self.curLvProcessLbl:setString(tostring(msg.exp.."/"..tostring(self.levelConfig.expNeed)))
    self.curLvLoadingBar:setPercent(msg.exp/checknumber(self.levelConfig.expNeed) * 100)

    local ft = SecretManager:getCurrentSecretTask()
    if ft then
        self.taskIcon:setTouchEnabled(true)
        self.taskTitleLbl:setString(string.format(L("lua_code_text_219"), tostring(checknumber(ft.needProgress)) )      )
        self.taskProcessLbl:setString(tostring(checknumber(ft.nowProgress)).."/"..tostring(checknumber(ft.needProgress)))
        self.taskLoadingBar:setPercent(checknumber(ft.nowProgress)/math.max(1, checknumber(ft.needProgress)) * 100)
        if checknumber(ft.nowProgress) >= checknumber(ft.needProgress) then
            self.taskMask:hide()
            self.taskLock:hide()
            -- self.taskIcon:hide()
            -- self.taskIcon2:show()
            self.mUINode:getTimeline():play("box", true)
        else
            if self.mUINode:getTimeline() then
                self.mUINode:getTimeline():pause()
            end
            self.taskMask:show()
            self.taskLock:show()
            -- self.taskIcon:show()
            -- self.taskIcon2:hide()
        end
    else
        self.taskIcon:setTouchEnabled(false)
        self.taskTitleLbl:setString(L("secret_allmission_finished"))
        self.taskProcessLbl:setString(L(""))
        self.taskLoadingBar:setPercent(100)
        self.mUINode:stopAllActions()
        self.taskIcon:hide()
        self.taskLock:hide()
        self.taskMask:hide()
        self.taskFinished:show()
        -- SecretManager:reqestSecretInfo()   
    end

    if msg.layer >= msg.initLayer + SecretManager.maxLayer or GD:getDungeonSecretModeConfigById(msg.layer+1) == nil then
        if GD:getDungeonSecretModeConfigById(msg.lv+1) == nil then
            self.curLvProcessLbl:setString("MAX")
            self.curLvLoadingBar:setPercent(1 * 100)
        end
        self:refreshMaxPanel()
        return
    end
    if GD:getDungeonSecretModeConfigById(msg.lv+1) == nil then
        self.curLvProcessLbl:setString("MAX")
        self.curLvLoadingBar:setPercent(1 * 100)
    end

    local tcfg = SecretManager:getGradesFromLayer(msg.layer)

    local function trans(aT)
        local t = tonumber(aT)
        local m = math.floor(t/60)
        local s = math.fmod(t, 60)

        return string.format("%d:%02d", m, s)
    end

    self.cups[1]:findChild("Panel/tlt"):setString(L("lua_code_text_288"))
    self.cups[2]:findChild("Panel/tlt"):setString(L("lua_code_text_228"))
    self.cups[3]:findChild("Panel/tlt"):setString(L("lua_code_text_462"))

    self.cups[1]:findChild("Panel/icon"):loadTexture(Res.teamUIPath .. "team_trophy_icon_3.png", 1)
    self.cups[2]:findChild("Panel/icon"):loadTexture(Res.teamUIPath .. "team_trophy_icon_2.png", 1)
    self.cups[3]:findChild("Panel/icon"):loadTexture(Res.teamUIPath .. "team_trophy_icon_1.png", 1)

    for i = 1, 3 do 
        self.cups[i]:findChild("Panel/time"):setString(tcfg[i].hmstr)
        if i <= curGrade then
            self.cups[i]:findChild("Panel/bg/num"):hide()
            self.cups[i]:findChild("Panel"):reorderChild(self.cups[i]:findChild("Panel/icon_over"), 100)
            self.cups[i]:findChild("Panel/icon_over"):show()
            -- self.cup_bgs[i]:setColor(cc.c3b(59, 15, 15))
        else
            self.cups[i]:findChild("Panel/bg/num"):show()
            self.cups[i]:findChild("Panel/icon_over"):hide()
            self.cups[i]:findChild("Panel/bg/num"):setString(tcfg[i].str)
            -- self.cup_bgs[i]:setColor(cc.c3b(102, 96, 85))
        end
    end

    --bg
    local thirdCfg = GD:queryTeamTargetById(msg.dungeonSubId)
    if thirdCfg and thirdCfg.dungeonBg then
        self.backgroundImg:loadTexture(Res.teamtarget_pic .. thirdCfg.dungeonBg .. ".png")
    end    
end

function SecretView:showNewSeasonPopView()
    local view = PvpLevelView.new()
    view:onCloseView(function(sender)
        app:sendMsg("BoxController", "openView", { boxType = Enums.BoxType.secret })
        UIHandler:removePopupUiByKey(sender:getViewName())
    end)

    local msg = SecretManager.info

    local sd = os.date("*t", msg.startTime)
    local ed = os.date("*t", msg.endTime)
    local str = string.format(L("lua_code_text_385"), tostring(sd.month), tostring(sd.day), tostring(ed.month), tostring(ed.day))

    local arg = {
        title1 = L("lua_code_text_134"),
        title2 = L("lua_code_text_279"),
        lv = msg.lv,
        tips1 = L("lua_code_text_497"),
        tips2 = str,
    }
    view:refreshSecret(arg)
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
end

function SecretView:addCloseListener()
    local btnClose = self.mUINode:findChild("Panel/Button_close")
    btnClose:addClickEventListener(function(sender)
        UIHandler:getSystemUi():removeSystemUiByKey("m_secretController")
    end)
end

return SecretView
